package cc.grapevine.vps;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
import cc.grapevine.vps.http.HttpClient;
import cc.grapevine.vps.http.URLManager;
import cc.grapevine.vps.util.NetWorkUtil;

public class Self2hostLogin extends Activity
{
	public static final int HTTP_ERROR = 0;
	public static final int USER_PASSWORD_ERROR = -1;
	public static final int USER_LOGIN_SUCCESS = 1;

	private EditText m_UserNameEditText;
	private EditText m_PasswordEditText;

	private String m_UserName;
	private String m_Passoword;

	private ProgressDialog m_LoginLoading;

	private UserManager m_Manager;

	private String TAG = getClass().getSimpleName();

	private SharedPreferences m_sharedPreferences;
	private AlertDialog setting;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		m_Manager = UserManager.getIntence();
		m_sharedPreferences = getSharedPreferences(TAG, MODE_PRIVATE);
		m_UserNameEditText = (EditText) findViewById(R.id.login_username);
		m_PasswordEditText = (EditText) findViewById(R.id.loogin_password);

		m_UserNameEditText.setText(m_sharedPreferences.getString(Configuration.LOGIN_EMAIL, ""));
		m_PasswordEditText.setText(m_sharedPreferences.getString(Configuration.LOGIN_PASSWORD, ""));

		findViewById(R.id.login_enter).setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (validate())
				{
					m_LoginLoading.show();
					new Thread(login).start();
				}
				else
				{
					showToast(R.string.login_validate_error);
				}
			}
		});
		m_LoginLoading = new ProgressDialog(this);
		m_LoginLoading.setTitle(R.string.login_pdg_title);
		m_LoginLoading.setMessage(getText(R.string.login_pdg_msg));
		m_LoginLoading.setCancelable(false);
		if (!NetWorkUtil.isLive(this))
		{
			Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(R.string.login_network_error_title);
			builder.setMessage(R.string.login_network_error_message);
			builder.setNegativeButton(R.string.login_network_error_setting, new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					setting.dismiss();
					Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
					Self2hostLogin.this.finish();
				}
			});
			builder.setCancelable(false);
			setting = builder.create();
			setting.show();
		}
	}

	private boolean validateEmail(String email)
	{
		String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(email);

		return m.find();
	}

	public boolean validate()
	{
		m_UserName = m_UserNameEditText.getText().toString().trim();
		m_Passoword = m_PasswordEditText.getText().toString().trim();

		if (null == m_UserName || !validateEmail(m_UserName))
		{
			m_UserNameEditText.requestFocus();
			return false;
		}

		if (null == m_Passoword || !(m_Passoword.length() >= 6 && m_Passoword.length() <= 20))
		{
			m_PasswordEditText.requestFocus();
			return false;
		}
		return true;
	}

	Runnable login = new Runnable()
	{

		@Override
		public void run()
		{
			HashMap<String, String> param = new HashMap<String, String>();
			param.put("email", m_UserName);
			param.put("password", m_Passoword);
			HttpClient client = new HttpClient();
			try
			{
				String result = client.postMethod(URLManager.LOGIN, param, "utf-8");
				int code = Integer.parseInt(result);
				if (code == USER_LOGIN_SUCCESS)
				{
					handler.sendEmptyMessage(USER_LOGIN_SUCCESS);
				}
				else
				{
					handler.sendEmptyMessage(USER_PASSWORD_ERROR);
				}
			}
			catch (Exception e)
			{
				handler.sendEmptyMessage(HTTP_ERROR);
			}
		}
	};

	public boolean onKeyDown(int keyCode, android.view.KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
			am.restartPackage(getPackageName());
		}

		return super.onKeyDown(keyCode, event);
	};

	protected void onDestroy()
	{
		super.onDestroy();
	};

	private void showToast(int resId)
	{
		Toast.makeText(Self2hostLogin.this, resId, Toast.LENGTH_SHORT).show();
	}

	Handler handler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			m_LoginLoading.dismiss();
			switch (msg.what)
			{
			case HTTP_ERROR:
				showToast(R.string.http_error);
				break;
			case USER_LOGIN_SUCCESS:

				Editor editor = m_sharedPreferences.edit();
				editor.putString(Configuration.LOGIN_EMAIL, m_UserName);
				editor.putString(Configuration.LOGIN_PASSWORD, m_Passoword);
				editor.commit();
				m_Manager.setUserName(m_UserName);
				m_Manager.setPassword(m_Passoword);
				startActivity(new Intent(Self2hostLogin.this, ListVpsActivity.class));
				Self2hostLogin.this.finish();
				break;
			case USER_PASSWORD_ERROR:
				showToast(R.string.login_information_error);
				break;
			default:
				super.handleMessage(msg);
				break;
			}

		};
	};

}